package com.offcn.search.controller;

import com.offcn.search.feign.SearchSkuFeign;
import com.offcn.search.pojo.SkuInfo;
import com.offcn.search.utils.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
@RequestMapping(value = "/search")
public class SkuController {

    @Autowired
    private SearchSkuFeign searchSkuFeign;
    /*** 搜索 * @param searchMap * @return */

    @GetMapping(value = "/list")
    public String search(@RequestParam(required = false) Map<String,String> searchMap, Model model){
        Map<String,Object> resultMap = searchSkuFeign.search(searchMap);
        model.addAttribute("result",resultMap);
        //3.设置搜索的条件 回显
        model.addAttribute("searchMap",searchMap);
        //4.记住之前的URL
        // 拼接url
        String url = this.setUrl(searchMap);
        model.addAttribute("url",url);
        Page<SkuInfo> page = new Page<SkuInfo>(
                Long.parseLong(resultMap.get("total").toString()),
                Integer.valueOf(resultMap.get("pageNum").toString()),
                Integer.valueOf(resultMap.get("pageSize").toString())
        );
        model.addAttribute("page",page);
        return "search1";
    }

    private String setUrl(Map<String, String> searchMap) {
        String url = "/search/list";
        if(searchMap!=null && searchMap.size()>0){
            url+="?";
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {
                String key = entry.getKey();// keywords / brand / category
                String value = entry.getValue();//华为 / 华为 / 笔记 本
                //如果是排序 则 跳过 拼接排序的地址 因为有数据
                if(entry.getKey().equals("sortField") || entry.getKey().equals("sortRule")){
                    continue;
                }
                if(key.equals("pageNum")){
                    continue;
                }
                url+=key+"="+value+"&";
            }
            //去掉多余的&
            if(url.lastIndexOf("&") != -1){
                url = url.substring(0,url.lastIndexOf("&"));
            }
        }
        return url;
    }
}
